Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vite: Cannot use import statement outside a module

Tags:

node.js

npm

vite

I know little about bundler and I'm using vite to build project, I got a error when import some package to configure dev server :

SyntaxError: Cannot use import statement outside a module

So here is the thing:

import pinyin from 'pinyin/esm/pinyin-web.js'

export const somePlugin = {
  name: 'someplugin',
  configureServer(server) {
    server.middlewares.use('/somepath', (req, res, next) => {
      const foo = pinyin('foo')
      next()
    })
  },
}

I don't use the normal way(import pinyin from 'pinyin') , because that need a package nodejieba which need to install unnecessary node-gyp, so I choose the web version that don't need nodejieba.

I've searched the error, some says add "type": "module" to package.json file. but it already exist in my package.json.

however, I make the change:

// import pinyin from 'pinyin/esm/pinyin-web.js'
import pinyin from 'pinyin/lib/pinyin-web.js'

and problem get solved,I was confused because I thought vite prefer ES module.

So, 1> what cause the problem above?

2> why should I import file with extensions ? eg: import pinyin from 'pinyin/lib/pinyin-web.js' I have to add extensions .js or it will cause error. while in vite.config.ts I needn't add extensions.

3> I tried to add field optimizeDeps in vite.config.ts like this

export default defineConfig({
  plugins: [vue(), somePlugin],
  optimizeDeps: {
    include: ['pinyin'],
  },
})

but it seems to be useless, the offical doc says:

"During development, Vite's dev serves all code as native ESM. Therefore, Vite must convert dependencies that are shipped as CommonJS or UMD into ESM first."

did that work for the frontend part and package "pinyin" is for the dev server so whether add the field optimizeDeps there is no difference.

codesandbox

like image 205
Archsx Avatar asked Aug 07 '26 07:08

Archsx


1 Answers

I had a similar problem that I was able to solve by adding

ssr: {
  noExternal: ['packageName'],
}

to my vite.config.js file.

like image 193
feus4177 Avatar answered Aug 09 '26 22:08

feus4177



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!